package com.dsp.soundscape.server;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;

import com.dsp.soundscape.config.filesystem.PathType;
import com.dsp.soundscape.model.AlbumInfo;
import com.dsp.soundscape.model.VersionInfo;

public class SoundscapeLoader implements Serializable {
	private static final long serialVersionUID = -8516781950851855518L;

	private static Logger log = Logger.getLogger(SoundscapeLoader.class.toString());
	
	private ConfigManager configuration;
	private ThumbnailScanner thumbnails;
	private SongScanner songs;

	@Autowired
	public void setConfiguration(ConfigManager configuration) {
		this.configuration = configuration;
	}

	@Autowired
	public void setThumbnails(ThumbnailScanner thumbnails) {
		this.thumbnails = thumbnails;
	}

	@Autowired
	public void setSongs(SongScanner songs) {
		this.songs = songs;
	}

	private List<String> getFolders() {
		if (configuration.getConfiguration().getMusic() != null && configuration.getConfiguration().getMusic().getPath() != null) {
			List <String> paths = new ArrayList <String>();
			for (PathType musicdir : configuration.getConfiguration().getMusic().getPath()) {
				File parentDir = new File(configuration.getPathroot() + musicdir.getDir());
				File[] dirs = parentDir.listFiles();
				for (File dir : dirs) {
					if (dir.isDirectory()) {
						String path = musicdir.getDir() + "/" + dir.getName();
						paths.add(path);
					}
				}
			}
			
			return paths;
			
		} else {
			log.warning("No Directories Defined");
			return null;
		}
	}
	
	public void thumbnails(AlbumInfo info) {
		thumbnails.scan(info);
	}
	
	public void populate(AlbumInfo info) {
		songs.scan(info);
	}
	
	public SoundscapeDataset getDataSet() {
		SoundscapeDataset dataset = new SoundscapeDataset();
		for (String path : getFolders()) {
			AlbumInfo album = new AlbumInfo();
			album.setFullpath(path);
			
			if (album.getYear() != null && album.getArtist() != null) {
				dataset.add(album);
			} else {
				log.warning("Null Values, Ignoring Album: " + album);
			}
		}
		
		return dataset;
	}

	public VersionInfo getVersion() {
		return configuration.getVersion();
	}
}